﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NewZealandCoffee.model
{
    public class IOMsg
    {
        private static IOMsg instance;
        private IOMsg() { }

        public static IOMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new IOMsg();
                }
                return instance;
            }
        }
        #region IO通讯
        public bool AllBol = true;
        public bool RobotBol = true;
        public delegate void IOdelegate(string btnName, string tag);
        public IOdelegate iodelegate;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        string nostrs = "";
        public Thread All_thr;
        public void QK()
        {
            try
            {
                IOMsg.Instance.AllBol = false;
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_KFJ_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_XN1_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_XN2_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_BQL_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_GJ1_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_GJ2_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_GJ3_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_GS1_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_GS2_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJB_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJC_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJXN_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJBQL_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBQLWC_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JGJWC_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JGSWC_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBWC_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBSWC_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBQL1_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBQL2_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBQL3_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBSB_Down);
                Thread.Sleep(100);
                IOMsg.Instance.AllBol = true;
            }
            catch (Exception)
            {
                return;
            }
        }
        public void QKCoffee()
        {
            try
            {
                IOMsg.Instance.AllBol = false;
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJB3_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJC3_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBSB3_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBCG3_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QFB1_Down);
                Thread.Sleep(100);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QFB2_Down);
                Thread.Sleep(100);
                IOMsg.Instance.AllBol = true;
            }
            catch (Exception)
            {
            }
        }
        public void IOSerial_Thr()
        {
            try
            {
                var ddd = SerialPort.GetPortNames().ToList();
                if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.PortName)))
                {
                    Thread.Sleep(1000);
                    IOSerial_Thr();
                }
                IOSerialPort.Instance.IceMachineConnect(IPorPortInfo.Instance.PortName, 38400, "", 8, 1);//其他串口通讯
                IOSerialPort.Instance.serialPort.DataReceived += SerialPort_DataReceived;
                Robot_Thr();
                All_thr = new Thread(AllMessages);
                All_thr.IsBackground = true;
                All_thr.Start();
            }
            catch (Exception)
            {
                IOSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        public void Robot_Thr()
        {
            try
            {
                // RobotOperate.Read_CSV(); //读取轨迹文件
                 RobotOperate.Instance.Robot_Initialisation_double(); //机器人初始化
            }
            catch (Exception)
            {
                Thread.Sleep(100);
                Robot_Thr();
            }
        }
        /// <summary>
        /// PING 通 IP
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public bool PingIP(string IP)
        {
            try
            {
                if (IP.Split('.').Count() < 4) return false;
                Ping pingSender = new Ping();
                PingReply reply = pingSender.Send(IP, 120);//第一个参数为ip地址，第二个参数为ping的时间
                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    //ping不通
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        public void AllMessages()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        if (Instance.AllBol)
                            IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.AllMessage);
                        Thread.Sleep(100);
                    }
                    catch (Exception)
                    {
                        Thread.Sleep(100);
                    }

                }
            }
            catch (Exception)
            {
                IOSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                byte[] result = new byte[IOSerialPort.Instance.serialPort.BytesToRead];
                IOSerialPort.Instance.serialPort.Read(result, 0, IOSerialPort.Instance.serialPort.BytesToRead);
                string str = "";// $"{DateTime.Now}：\n";
                str += $"{Encoding.ASCII.GetString(result)}";
                for (int i = 0; i < result.Length; i++)
                {
                    str += $"{result[i].ToString("X2")} ";
                }
                MsgShow(str);
                Thread.Sleep(1);
            }
            catch (Exception)
            {
                return;
            }
        }
        public void DigitalMsgBol2(string str)
        {
            try
            {

                var Bol = str.Split(' ');
                bool bol = false;
                if (WuLiaoIceSel.Instance.BANNER_Sel_Bol != (Bol[4] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.BANNER_Sel_Bol = Bol[4] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.PushRodUP_Sel_Bol != (Bol[6] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.PushRodUP_Sel_Bol = Bol[6] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.PushRodDown_Sel_Bol != (Bol[8] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.PushRodDown_Sel_Bol = Bol[8] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.OutMealCup_Sel_Bol != (Bol[10] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.OutMealCup_Sel_Bol = Bol[10] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.CupFeed1_Sel_Bol != (Bol[12] == "01" ? true : false))
                {
                    WuLiaoIceSel.Instance.IsWLBol = true;
                    bol = true;
                }
                WuLiaoIceSel.Instance.CupFeed1_Sel_Bol = Bol[12] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.CupFeed2_Sel_Bol != (Bol[14] == "01" ? true : false))
                {
                    WuLiaoIceSel.Instance.IsWLBol = true;
                    bol = true;
                }
                WuLiaoIceSel.Instance.CupFeed2_Sel_Bol = Bol[14] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.TakeCup_Sel_Bol != (Bol[16] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.TakeCup_Sel_Bol = Bol[16] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.LBQFK1_Bol != (Bol[18] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.LBQFK1_Bol = Bol[18] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.TakeCup2_Sel_Bol != (Bol[20] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.TakeCup2_Sel_Bol = Bol[20] == "01" ? true : false;

                if (WuLiaoIceSel.Instance.IsICeMaterial1 != (Bol[22] == "01" ? true : false))
                {
                    WuLiaoIceSel.Instance.IsWLBol = true;
                    bol = true;
                }
                WuLiaoIceSel.Instance.IsICeMaterial1 = Bol[22] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.IsICeMaterial2 != (Bol[24] == "01" ? true : false))
                {
                    WuLiaoIceSel.Instance.IsWLBol = true;
                    bol = true;
                }
                WuLiaoIceSel.Instance.IsICeMaterial2 = Bol[24] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.LBQFK2_Bol != (Bol[26] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.LBQFK2_Bol = Bol[26] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.IceCup1_Bol != (Bol[28] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.IceCup1_Bol = Bol[28] == "01" ? true : false;
                if (WuLiaoIceSel.Instance.IceCup2_Bol != (Bol[30] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoIceSel.Instance.IceCup2_Bol = Bol[30] == "01" ? true : false;
                if (bol)
                {
                    ClientList clientList = new ClientList();
                    clientList.MsgIceBol = WuLiaoIceSel.Instance;
                    clientList.code = 1;
                    SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                    WuLiaoIceSel.Instance.IsWLBol = false;
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        public void MsgShow(string str)
        {
            try
            {
                //Console.WriteLine(str);
                int count = str.Length / 315;
                if (count > 0)
                {
                    var str1 = str.Substring(str.Length - count * 315, 315);
                    //Console.WriteLine(str1);
                    if (str1.Split(' ').Count() == 105)
                    {
                        DigitalMsgBol2(str1);
                        if (count > 1)
                            MsgShow(str.Substring(str.Length - (count - 1) * 315, (count - 1) * 315));
                    }
                    else
                    {
                        var nostr = str1.Split(' ');
                        int cc = int.TryParse(nostr[0].Substring(nostr[0].Length - 2, 2), out int a) ? a : -1;
                        if (cc != -1)
                        {
                            nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
                            for (int i = 1; i < nostr.Count() - 1; i++)
                            {
                                nostrs += nostr[i] + " ";
                            }
                            // Console.WriteLine(nostrs);
                            if (nostrs.Substring(0, 5) == "02 04")
                            {
                                if (nostrs.Count() >= 315)
                                {
                                    DigitalMsgBol2(nostrs);
                                    nostrs = "";
                                }
                            }
                            else
                            {
                                nostrs = "";
                            }
                        }
                    }
                }
                else
                {

                    var nostr = str.Split(' ');
                    nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
                    for (int i = 1; i < nostr.Count() - 1; i++)
                    {
                        nostrs += nostr[i] + " ";
                    }
                    // Console.WriteLine(nostrs);
                    if (nostrs.Substring(0, 5) == "02 04")
                    {
                        if (nostrs.Count() >= 315)
                        {
                            DigitalMsgBol2(nostrs);
                            nostrs = "";
                        }
                    }
                    else
                    {
                        if (nostrs.Substring(0, 5) == "01 05")
                        {
                            Console.WriteLine(str);
                        }
                        else if (nostrs.Substring(0, 5) == "02 04")
                        {
                            Console.WriteLine(nostrs);
                            if (nostrs.Contains("02 04 02 00 01 3C F0"))
                            {
                                //  DigitalMsgBol.Instance.JBCGJC_Bol = true;
                            }
                        }
                        else if (nostrs.Substring(0, 5) == "03 02")
                        {
                            Console.WriteLine(nostrs);
                            var robstr = nostrs.Split(' ');
                            RobotBol = robstr[3] == "01" ? true : false;
                            Console.WriteLine(robstr[3] == "01" ? true : false);
                        }
                        else if (nostrs.Substring(0, 5) == "04 02")
                        {
                            Console.WriteLine(nostrs);
                            var robstr = nostrs.Split(' ');
                            RobotBol = robstr[3] == "01" ? true : false;
                            Console.WriteLine(robstr[3] == "01" ? true : false);
                        }
                        nostrs = "";
                    }
                }

            }
            catch (Exception)
            {
                return;
            }
        }
        #endregion
    }
}
